package com.sise.dubbo.spi.myspi;

import com.sise.dubbo.spi.spidemo.UserService;
import com.sise.dubbo.spi.spidemo.UserServiceImpl;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.URL;
import java.util.Enumeration;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

/**
 * @author idea
 * @date 2019/5/17
 */
public class MySpiUtil {

    private static final String SPI_DIR = "META-INF/idea/";

    private Map<String, Class<?>> classMap = new ConcurrentHashMap<>();

    /**
     * 加载目录底下的文件信息
     *
     * @param clazz
     */
    public void loadDirectory(Class clazz) {
        String fileName = SPI_DIR + clazz.getName();
        ClassLoader classLoader = this.getClass().getClassLoader();
        try {
            Enumeration<URL> resources = classLoader.getResources(fileName);
            if (resources != null) {
                while (resources.hasMoreElements()) {
                    URL url = resources.nextElement();
                    loadResource(classLoader, url);
                }
            }
        } catch (IOException e) {
            e.printStackTrace();
        }

    }


    public void loadResource(ClassLoader classLoader, URL url) {
        //读取配置文件里面的内容
        try {
            BufferedReader reader = new BufferedReader(
                    new InputStreamReader(url.openStream(), "utf-8"));
            String line;
            while ((line = reader.readLine()) != null) {
                int c = line.indexOf("#");
                //该行内容没有注释
                if (c <= 0) {
                    line = line.trim();
                    if (line.length() > 0) {
                        int splitIndex = line.indexOf("=");
                        String name = line.substring(0, splitIndex).trim();
                        String className = line.substring(splitIndex + 1).trim();
                        classMap.put(name, Class.forName(className, true, classLoader));
                    }

                }
            }
        } catch (IOException e) {
            e.printStackTrace();
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        }
    }


    public static void main(String[] args) throws IllegalAccessException, InstantiationException {
        MySpiUtil mySpiUtil = new MySpiUtil();
        mySpiUtil.loadDirectory(UserService.class);
        UserServiceImpl userService = (UserServiceImpl) mySpiUtil.classMap.get("UserService").newInstance();
        userService.say();
    }
}
